package com.gzx.risk.core.service.impl;

import com.gzx.risk.core.service.ILockControlService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LockControlServiceImpl implements ILockControlService {

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public boolean tryLock(String key) {
        return tryLock(key,15, TimeUnit.SECONDS); //默认15s
    }

    @Override
    public boolean tryLock(String key, long waitTime, TimeUnit unit) {
        try {
            return getRLock(key).tryLock(waitTime, unit);
        } catch (Exception e) {
            log.error("获取分布式锁出现异常, key : {}", key, e);
            return false;
        }
    }

    @Override
    public boolean tryDebounce(String key, long expireTime, TimeUnit timeUnit) {
        try {
            // 尝试设置一个带过期时间的 key，如果已存在则返回 false
            return redissonClient.getBucket(key).trySet("1", expireTime, timeUnit);
        } catch (Exception e) {
            log.error("防抖检查异常, key: {}", key, e);
            return true;
        }
    }


    @Override
    public void unlock(String lockKey) {
        RLock rLock = getRLock(lockKey);
        if (rLock != null && rLock.isHeldByCurrentThread()) {
            rLock.unlock();
        }
    }

    /**
     * 根据 key 获取RLock
     *
     * @param lockKey
     * @return
     */
    private RLock getRLock(String lockKey) {
        return redissonClient.getLock(lockKey);
    }
}